package util

import (
	"encoding/json"
	"fmt"
	"hepan1/src/setting"
	"io/ioutil"
	"math/rand"
	"net/http"
	"strings"
	"time"
)

// WeightedRandomIndex 从weights中按照加权抽取一个数,返回抽到的
func WeightedRandomIndex(weights []float64) int {
	if len(weights) == 1 {
		return 0
	}
	var sum float32 = 0.0
	for _, w := range weights {
		sum += float32(w)
	}
	rand.Seed(time.Now().UnixNano())
	r := rand.Float32() * sum
	var t float32 = 0.0
	for i, w := range weights {
		t += float32(w)
		if t > r {
			return i
		}
	}
	return len(weights) - 1
}

func Check(err error) bool {
	if err == nil {
		return false
	}
	fmt.Println("有些错误")
	return true
}

//发送http请求
func HttpDo(code string) (int,string,string){
	//client := &http.Client{}
	//// 使用 NewRequest 设置头参数、cookie之类的数据，
	//req, err := http.NewRequest("POST", "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code", strings.NewReader("name=cjb"))
	//if err != nil {
	//	// handle error
	//}
	//
	//req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	//req.Header.Set("Cookie", "name=anny")
	//
	//resp, err := client.Do(req)
	//
	//defer resp.Body.Close()
	//
	//body, err := ioutil.ReadAll(resp.Body)
	//if err != nil {
	//	// handle error
	//}
	//
	//fmt.Println(string(body))
	client := &http.Client{}
	url := fmt.Sprintf("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",setting.AppID,setting.AppSecret,code)
	fmt.Println(url)
	req, err := http.NewRequest("get", url, strings.NewReader(""))
	if err != nil {
		return -2,err.Error(),""
	}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36")
	req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9")
	req.Header.Set("Cookie", "name=anny")
	//req.
	resp, err := client.Do(req)
	if err != nil {
		return -2,err.Error(),""
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return -2,err.Error(),""
	}
	resString := string(body)
	var resMap map[string]interface{}

	err = json.Unmarshal([]byte(resString), &resMap)

	if err != nil {
		fmt.Println("string转map失败", err)
	}

	fmt.Println("下面是resmap")
	fmt.Println(resMap)
	fmt.Println(resMap["errcode"])
	fmt.Println(resMap["openid"])
	//fmt.Printf("%T\n",resMap["errcode"])
	if resMap["errcode"]==nil{
		fmt.Println("errcode是没有的")
	}else {
		return int(resMap["errcode"].(float64)),resMap["errmsg"].(string),""
	}
	fmt.Println(string(body))
	openid := resMap["openid"]
	if len(openid.(string))==0{
		return -2,"未知原因",""
	}
	fmt.Println("这里有问题吗1")
	fmt.Println(openid.(string))
	fmt.Println("这里有问题吗2")
	return 0,"",openid.(string)
}

// GetRandomString 随机生成字符串
func GetRandomString(l int) string {
	str := "0123456789abcdefghijklmnopqrstuvwxyz"
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < l; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}
	return string(result)
}